package com.example.controller;

import com.example.model.DateMessage;
import com.example.model.DateMessageSum;
import com.example.service.IDateMessageService;
import com.example.service.IDateMessageSumService;
import com.example.service.impl.DateMessageServiceImpl;
import com.example.service.impl.DateMessageSumServiceImpl;
import com.example.utils.*;
import com.example.utils.image.ImageUtils;
import com.example.utils.image.RedisUtil;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.summary.TextRankSentence;
import org.meowy.cqp.jcq.entity.CoolQ;
import org.meowy.cqp.jcq.message.CQCode;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class MessageController {

    public void addMessage(DateMessage dateMessage){
        IDateMessageService dateMessageService = new DateMessageServiceImpl();
        dateMessageService.addDateMessage(dateMessage);
    }


    public String getMySelfMessageSum(String msg, Long fromGroup, Long fromQQ, CoolQ CC){
        StringBuilder stringBuilder = new StringBuilder();
        Long tempQQ = 0L;
        String [] arr = msg.split("\\s+");
        int type = 1;
        String day = "今天";

        for (int i = 0; i < arr.length; i++) {
            String str_temp = arr[i];
            if(StringUtils.isNotEmpty(str_temp)){
                if(StringUtils.isNumString(str_temp)){
                    tempQQ = Long.parseLong(str_temp);
                }else {
                    if(str_temp.contains("今天")){
                        type=1;day="今天";
                    }else if(str_temp.contains("昨天")){
                        type=2;day="昨天";
                    }else if(str_temp.contains("本周")){
                        type=3;day="本周";
                    }else if(str_temp.contains("本月")){
                        type=4;day="本月";
                    }else if(str_temp.contains("本年")){
                        type=5;day="本年";
                    }
                }
            }
        }

        if(tempQQ <= 10001){
            tempQQ = fromQQ;
        }

        MyLog.log(fromGroup+"--"+fromQQ);
        IDateMessageSumService dateMessageSumService = new DateMessageSumServiceImpl();
        IDateMessageService dateMessageService = new DateMessageServiceImpl();
        DateMessageSum mySelfMessageSum = dateMessageSumService.getMySelfMessageSum(DateUtils.getTypeDate(type)[0], DateUtils.getTypeDate(type)[1], fromGroup, tempQQ);


        String nick = CC.getGroupMemberInfo(fromGroup,tempQQ).getCard();
        if(StringUtils.isEmpty(nick))nick = CC.getGroupMemberInfo(fromGroup,tempQQ).getNick();

        if(tempQQ.equals(fromQQ)){nick+=" 您";}
        if(mySelfMessageSum != null){
            CQCode CQ = CQCode.getInstance();
            stringBuilder.append(nick).append(day).append("\n")
                    .append("首次发言: ").append(DateUtils.getYYYYMMDDTime(mySelfMessageSum.getStartTime())).append("\n")
                    .append("最后发言: ").append(DateUtils.getYYYYMMDDTime(mySelfMessageSum.getEndTime())).append("\n")
                    .append("统计消息: ").append(mySelfMessageSum.getMessageNum()).append("条\n")
                    .append("统计字符: ").append(mySelfMessageSum.getCharNum() == null?"无":mySelfMessageSum.getCharNum()).append("个\n");

            List<DateMessage> allDateMessages = dateMessageService.queryByGroupId(DateUtils.getTypeDate(type)[0], DateUtils.getTypeDate(type)[1],fromGroup);
            List<DateMessage> dateMessages = dateMessageService.queryByGroupIdAndQQ(DateUtils.getTypeDate(type)[0], DateUtils.getTypeDate(type)[1],fromGroup, tempQQ);

            int emojiSum = 0;
            int faceSum = 0;
            String imageSum = null;
            Long at = 0L;

            if(dateMessages != null && dateMessages.size() >0){
                StringBuilder messages = new StringBuilder();
                for (DateMessage dateMessage : dateMessages) {
                    messages.append(dateMessage.getMessageContent());
                }

                String message = messages.toString();
                if(StringUtils.isNotEmpty(message)){
                    Map<String, List> all = StringUtils.getAll(message);
                    // emoji 表情列表
                    List<Integer> emojis = all.get("emojis");
                    // face 表情
                    List<Integer> faceIds = all.get("faces");
                    // 图片 图片列表
                    List<String> cqImages = all.get("images");
                    // 最喜欢AT
                    List<Long> ats = all.get("ats");
                    emojiSum = ListUtils.getListMaxFrequentlyInteger(emojis);
                    faceSum = ListUtils.getListMaxFrequentlyInteger(faceIds);
                    imageSum = ListUtils.getListMaxFrequentlyString(cqImages);
                    at = ListUtils.getListMaxFrequentlyLong(ats);
                }
            }

            // 活跃时间
            String str = PeriodUtils.period(dateMessageService,DateUtils.getTypeDate(type)[0], DateUtils.getTypeDate(type)[1],fromGroup, tempQQ);
            // 活跃贡献
            BigDecimal contribution = new BigDecimal("0.0");
            if(allDateMessages != null && dateMessages != null && allDateMessages.size() >0){
                contribution = new BigDecimal(dateMessages.size()).divide(new BigDecimal(allDateMessages.size()),4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            }
            String favorite = "";
            if(at >0 ){
                CC.getGroupMemberInfo(fromGroup, at).getCard();
                if(StringUtils.isEmpty(favorite))favorite=CC.getGroupMemberInfo(fromGroup, at).getNick();
            }
            String cat = "否";
            if(StringUtils.isNotEmpty(str)&&str.equals("子时")){
                cat = "夜猫子";
            }else if(StringUtils.isNotEmpty(str)&&(str.equals("丑时")||str.equals("寅时"))){
                cat = "超级夜猫子";
            }
            stringBuilder.append("最多Emoji: ").append(emojiSum <= 0 ? "无" : CQ.emoji(emojiSum)).append("\n")
                    .append("最多Face: ").append(faceSum <= 0 ? "无" : CQ.face(faceSum)).append("\n")
                    .append("最喜欢at: ").append(at <= 0 ? "无" : favorite).append("\n")
                    .append("活跃时间: ").append(StringUtils.isEmpty(str) ? "无" : str).append("\n")
                    .append("夜猫子否: ").append(cat).append("\n")
                    .append("群跃贡献: ").append(StatisticsUtils.getActiveEvaluation(contribution)).append("(").append(contribution.setScale(2, BigDecimal.ROUND_HALF_UP)).append("%)").append("\n")
                    .append("最多图片: ").append(StringUtils.isEmpty(imageSum)? "无":CQ.image(imageSum)).append("\n");

            // 生成词云图
            if(dateMessages != null && dateMessages.size() >0){
                StringBuilder messages = new StringBuilder();
                for (DateMessage dateMessage : dateMessages) {
                    messages.append(dateMessage.getMessageContent()).append("\n");
                }
                String ss2 = StringUtils.replaceAllCenterBrackets(messages.toString());
                //System.out.println(str);
                List<String> keywordList = HanLP.extractKeyword(ss2, 50);
                List<String> topSentenceList = TextRankSentence.getTopSentenceList(ss2, 20);
                topSentenceList.addAll(keywordList);
                int i = MathUtils.randInt(100, 0);
                String fileName = DateUtils.getYYYYMMDDHHMMSS()+".png";
                String filePath = "D:\\Application\\CQP_TULING\\data\\image\\words\\"+fileName;
                if(i>=50){
                    WordCloudUtils.wordCloud(topSentenceList,filePath);
                }else{
                    WordCloudUtils.wordCloud2(topSentenceList,filePath);
                }
                stringBuilder.append("词云图: ").append(CQ.image("/words/"+fileName)).append("\n");
            }else{
                stringBuilder.append("词云图: ").append("无").append("\n");
            }
            // 获取作息时间是否正常
            int rest = DateUtils.getRest(new Date());
            // 睡太晚
            if(rest == 1){
                List<String> list = RedisUtil.getList("coolq:rest:toolate");
                if(list != null && list.size() >0){
                    String rst = list.get(MathUtils.randInt(list.size()-1,0));
                    stringBuilder.append("你睡得太晚啦: ").append(rst).append("\n");
                }
            }
        }else {
            stringBuilder.append("没有查询到").append(nick).append("需要的信息呢~");
        }
        stringBuilder.append("\n 汇总 今天|昨天|本周|本月|本年  即可查询");
        return stringBuilder.toString();
    }

    /**
     *
     * @param type 1 今天 2 昨天 3 本周 4 本月 5 本年
     * @param fromGroup
     * @return
     */
    public String  getDragonKing(String msg,Long fromGroup,Long fromQQ, CoolQ CC){
        String [] arr = msg.split("\\s+");
        int type = 1;
        String str = "今天";

        if(arr.length >1&&StringUtils.isNotEmpty(arr[1])) {
            if(arr[1].contains("今天")){
                type=1;str="今天";
            }else if(arr[1].contains("昨天")){
                type=2;str="昨天";
            }else if(arr[1].contains("本周")){
                type=3;str="本周";
            }else if(arr[1].contains("本月")){
                type=4;str="本月";
            }else if(arr[1].contains("本年")){
                type=5;str="本年";
            }
        }

        IDateMessageSumService dateMessageSumService = new DateMessageSumServiceImpl();
        List<DateMessageSum> dragonKing = dateMessageSumService.getDragonKing(DateUtils.getTypeDate(type)[0], DateUtils.getTypeDate(type)[1], fromGroup);

        StringBuilder dragonKingStr = new StringBuilder();
        CQCode CQ = CQCode.getInstance();
        String firstName = "";
        if(dragonKing != null && dragonKing.size() >0){
            dragonKingStr.append("--->龙王榜(").append(str).append(")<---\n");
            int i = 1;
            for (DateMessageSum dateMessageSum : dragonKing) {
                if(i>10){break;}
                String nick = CC.getGroupMemberInfo(fromGroup,dateMessageSum.getQq()).getCard();
                if(StringUtils.isEmpty(nick))nick = CC.getGroupMemberInfo(fromGroup,dateMessageSum.getQq()).getNick();
                if(StringUtils.isEmpty(firstName))firstName = nick;
                dragonKingStr.append("第").append(i < 10 ? "0" : "").append(i).append(":【").append(nick).append("】 发言").append(dateMessageSum.getMessageNum()).append("条,字符").append(dateMessageSum.getCharNum()).append("个.\n");
                i+=1;
            }
        }
        // 添加龙王图片
        String dragonKingImage = ImageUtils.getDragonKingImage(firstName);
        dragonKingStr.append(CQ.image(dragonKingImage)).append("\n");
        dragonKingStr.append("\n 发送 龙王 今天|昨天|本周|本月|本年  即可查询");

        return dragonKingStr.toString();
    }
}
